package com.mars.nacos.domian.service.impl;

import com.google.common.collect.Maps;
import com.mars.nacos.domian.service.FlowableService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.*;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : kyrie
 * @date : 2022/9/7 10:01
 * #desc    : some description
 */
@Service
@Slf4j
public class FlowableServiceImpl implements FlowableService {

    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private ProcessEngine processEngine;

    @Override
    public String addExpense(String userId, Integer money, String desc) {
        Map<String, Object> itemMap = Maps.newHashMap();
        itemMap.put("taskUser", userId);
        itemMap.put("money", money);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("Expense", itemMap);
        return processInstance.getId();
    }

    @Override
    public Object findList(String userId) {
        List<Task> tasks = taskService.createTaskQuery().taskAssignee(userId).orderByTaskCreateTime().desc().list();
        for (Task task : tasks) {
            System.out.println(task.toString());
        }
        return "task size: " +tasks.size() + " , 第一个：" + tasks.get(0).toString() ;
    }

    @Override
    public String apply(String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            throw new RuntimeException("流程不存在");
        }
        //通过审核
        Map<String, Object> map = Maps.newHashMap();
        map.put("outcome", "通过");
        taskService.complete(taskId, map);
        return "processed ok!";
    }

    @Override
    public String reject(String taskId) {
        HashMap<String, Object> map = Maps.newHashMap();
        map.put("outcome", "驳回");
        taskService.complete(taskId, map);
        return "reject";
    }

    @Override
    public void genProcessDiagram(HttpServletResponse httpServletResponse, String processId) throws IOException {

    }
}
